import os

def menu ():
    print ("------------------------------")
    print ("*********** 1 查字 ***********")
    print ("*********** 2 补充 ***********")
    print ("*********** 3 移除 ***********")
    print ("*********** 0 退出 ***********")
    print ("------------------------------")
    
def serach ():
    os.system ('cls')
    print ()
    word = str (input ("请输入要查询的汉字: "))
    os.system ('cls')
    word_file = os.path.join (os.getcwd(), 'All_words' , 'all_words.txt') # 创建all_words路径
    words = open (word_file , 'r' , encoding='utf-8') # 打开all_words.txt并进行读操作
    if ((word + '\n') in words.readlines()): # 读取all_words.txt中的所有行，判断是否有该汉字
        one_word_file = os.path.join (os.getcwd(), 'All_words' , word + '.txt') # 创建该汉字的路径
        one_word = open (one_word_file , 'r' , encoding='utf-8') # 打开该汉字的文件并进行读操作
        lines = one_word.readlines() # 读取该汉字的所有行
        print ()
        for line in lines:
            print (line.strip()) # 输出该汉字的所有行，strip()函数用于去除行尾的空格
        print ()
        words.close()
        one_word.close()
        input ("按Enter键继续...")
        return os.system ('cls')
    else :
        print ()
        words.close()
        print ("未找到，是否要进行字库补充？(yes/no)")
        a = input ()
        if a == 'yes':
            return 2
        elif a == 'no':
            return 0 
        else :
            print ("输入有误，默认拒绝。")
            return 0    

def com (shengmu, yunmu, tone):
    all_yunmu0 = ['a','o','e','i','u','ü','er','ai','ei','ao','ou','an','en','ang','eng','ing','ong','ia','iao','ian','iong','uai','ue','uan','uang','ui','un']
    all_yunmu1 = ['ā','ō','ē','ī','ū','ū','ēr','āi','ēi','āo','ōu','ān','ēn','āng','ēng','īng','ōng','īa','īao','īan','īong','ūai','ūe','ūan','ūang','ūi','ūn']
    all_yunmu2 = ['á','ó','é','í','ú','ú','ér','ái','éi','áo','óu','án','én','áng','éng','íng','óng','ía','íao','ían','íong','uái','uē','uán','uáng','uī','ún']
    all_yunmu3 = ['ǎ','ǒ','ě','ǐ','ǔ','ǔ','ěr','ǎi','ěi','ǎo','ǒu','ǎn','ěn','ǎng','ěng','ǐng','ǒng','ǐa','ǐao','ǐan','ǐong','uǎi','uě','uǎn','uǎng','uǐ','ǔn']
    all_yunmu4 = ['à','ò','è','ì','ù','ù','èr','ài','èi','ào','òu','àn','èn','àng','èng','ìng','òng','ìa','ìao','ìan','ìong','uài','uè','uàn','uàng','uì','ùn']
    all_tone = ['1','2','3','4','5']
    # 12,13,14,22 ü变u
    if (tone == 5 and shengmu not in [12,13,14,22]):
        return all_yunmu0[yunmu - 1]
    elif (tone == 5 and shengmu in [12,13,14,22]):
        if (yunmu != 6):
            return all_yunmu0[yunmu - 1]
        else :
            return all_yunmu0[4]
    elif (tone == 1):
        return all_yunmu1[yunmu - 1]
    elif (tone == 2):
        return all_yunmu2[yunmu - 1]
    elif (tone == 3):
        return all_yunmu3[yunmu - 1]
    elif (tone == 4):
        return all_yunmu4[yunmu - 1]

def add ():
    os.system ('cls')
    print ()
    print ("------------注意事项------------")
    print ("1.每次仅能添加一个汉字")
    print ("2.请确保该字未在字库中")
    print ("3.字库编码为UTF-8")
    print ("4.请确保信息来源准确可靠(官方字词典等)")
    print ("5.书写顺序为：汉字，拼音，词性，释义，举例")
    print ("6.其他输入注意事项请参考后续提示")
    print ("-------------------------------")
    print ()
    input ("按Enter键继续...")
    
    # 添加汉字
    os.system ('cls')
    print ()
    print ("\033[1;31m注：若输入多个汉字仅保存首位汉字\033[0m")
    print ("\033[0;32m退出添加输入#\033[0m")
    word = str (input ("请输入要添加的汉字: "))
    word = word[0]
    if (word == '#'):
        print ()
        return 0
    try:
        word_file = os.path.join (os.getcwd(), 'All_words' , 'all_words.txt') # 创建all_words路径
        words = open (word_file , 'r' , encoding='utf-8') # 打开all_words.txt并进行读操作
        if ((word[0] + '\n') in words.readlines()): # 读取all_words.txt中的所有行，判断是否有该汉字
            os.system ('cls')
            print ()
            print ("字库中已有该汉字，请勿重复添加！")
            print ()
            raise ValueError
        words.close()
        words = open (word_file , 'a' , encoding='utf-8')
        words.write (word + '\n')
        one_word_file = os.path.join (os.getcwd(), 'All_words' , word + '.txt')
        one_word = open (one_word_file , 'w' , encoding='utf-8')
        one_word.write (word + '\n')
        os.system ('cls')
        print ()
        print ("已成功添加汉字：",word)
    except ValueError:
        words.close()
        return 0
        
    # 添加拼音
    while (True):
        try:
            print ()
            print ("请选择添加拼音方式：")
            print ("1.用户输入")
            print ("2.拼音库选择")
            chs = int (input ("请选择: "))
            print ()
            if (chs == 1):
                os.system ('cls')
                print ("\033[1;31m注：用户需要自行输入整个拼音和声调，例wǒ\033[0m")
                pinyin = str (input ("请输入拼音: "))
                one_word.write (pinyin)
            elif (chs == 2):
                os.system ('cls')
                print ("\033[1;31m注：为了方便用户输入，该拼音库已做出部分调整，声韵表会有部分有区别于官方规定！\033[0m")
                print ("请选择声母：")
                print ("1. b  2. p  3. m \n4. f  5. d  6. t \n7. n  8. l  9. g \n10.k  11.h  12.j \n13.q  14.x  15.zh \n16.ch 17.sh 18.r \n19.z  20.c  21.s \n22.y  23.w  24.0")
                shengmu = int (input ("请选择: "))
                if (shengmu < 1 or shengmu > 24):
                    os.system ('cls')
                    raise ValueError
                os.system ('cls')
                print ()
                print ("请选择韵母：")
                print ("1. a    2. o   3. e   4. i \n5. u    6. ü   7. er  8. ai \n9. ei   10.ao  11.ou  12.an \n13.en   14.ang 15.eng 16.ing \n17.ong  18.ia  19.iao 20.ian \n21.iong 22.uai 23.ue  24.uan \n25.uang 26.ui  27.un ")
                yunmu = int (input ("请选择: "))
                if (yunmu < 1 or yunmu >27):
                    os.system ('cls')
                    raise ValueError
                os.system ('cls')
                print ()
                print ("请选择声调：")
                print ("1.阴平 2.阳平 3.上声 4.去声 5.轻声")
                tone = int (input ("请选择: "))
                if (tone < 1 or tone > 5):
                    os.system ('cls')
                    raise ValueError
                all_shengmu = ['b','p','m','f','d','t','n','l','g','k','h','j','q','x','zh','ch','sh','r','z','c','s','y','w','']
                tone_yunmu = com (shengmu, yunmu, tone)
                one_word.write (all_shengmu[shengmu - 1] + tone_yunmu)
                pinyin = all_shengmu[shengmu - 1] + tone_yunmu
                print ()
            else:
                raise ValueError
            os.system ('cls')
            print ("已成功添加拼音：",pinyin)
            print ("是否要继续添加额外拼音？(yes/no)")
            a = input ()
            if (a == 'yes'):
                one_word.write ('/')
                print ()
            elif (a == 'no'):
                one_word.write ('\n')
                break
            else:
                os.system ('cls')
                print ("输入有误，默认拒绝。")
                one_word.write ('\n')
                break
        except ValueError:
            print ("选项错误，请重新选择。")  
    
    # 添加结构
    while (True):
        try:
            os.system ('cls')
            print ()
            print ("请选择汉字结构：")
            print ("1. 独体字\n2. 左右结构\n3. 上下结构\n4. 左中右结构\n5. 上中下结构\n6. 半包围结构\n7. 全包围结构\n8. 镶嵌结构")
            all_arch = ['独体字','左右结构','上下结构','左中右结构','上中下结构','半包围结构','全包围结构','镶嵌结构']
            arch = int (input ("请选择: "))
            if (arch < 1 or arch > 8):
                raise ValueError
            one_word.write (all_arch[arch - 1] + '\n\n')
            os.system ('cls')
            print ()
            print ("已成功添加汉字结构！")
            break
        except ValueError:
            os.system ('cls')
            print ("选项错误，请重新选择。")
    
    # 书写词性，释义，举例
    num = '1'
    while (True):
        try:
            print ()
            print ("请选择词性：")
            print ("1. 名词\n2. 动词\n3. 形容词\n4. 副词\n5. 代词\n6. 连词\n7. 介词\n8. 数词\n9. 量词\n10.助词\n11.感叹词\n12.拟声词")
            all_pos = ['名词','动词','形容词','副词','代词','连词','介词','数词','量词','助词','感叹词','拟声词']
            pos = int ( input ("请选择："))
            os.system ('cls')
            print ()
            if (pos < 1 or pos > 12):
                raise ValueError
            one_word.write (num + '.' + all_pos[pos - 1] + ' ')
        except ValueError:
            os.system ('cls')
            print ("选项错误，请重新选择。")
        while (True):
            print ("\033[1;31m释义结尾以#结束\033[0m")
            mean = str (input ("请输入其释义："))
            if ('#' in mean):
                break
            os.system ('cls')
            print ()
            print ("请用#结尾！")
            print ()
        for i in mean:
            if (i == '#'):
                break
            one_word.write (i)
        one_word.write ('\n')
        a = 1
        while (True):
            os.system ('cls')
            if (a==1):
                one_word.write ('----')
                a = 0
            print ("\033[1;31m例子之间由&隔开，结尾以#结束\033[0m")
            eg = str (input ("请输入其例词或例句："))
            if ('#' in eg):
                break
            os.system ('cls')
            print ()
            print ("请用#结尾！")
            print ()
        a = 1
        for i in eg:
            if (i == '#'):
                break
            elif (i == '&'):
                one_word.write ('|')
            else :
                one_word.write (i)
        os.system ('cls')
        print ()
        print ("所有释义内容均已添加！")
        print ("是否要继续添加额外释义？(yes/no)")
        a = input()
        if (a == 'yes'):
                one_word.write ('\n')
                num = str (int (num) + 1)
        elif (a == 'no'):
            break
        else:
            os.system ('cls')
            print ("输入有误，默认拒绝。")
            break
    os.system ('cls')
    print ()
    print (f"“{word}”汉字所有内容均已添加！")
    print ()
    one_word.close()
    return 0

def remove():
    os.system ('cls')
    print ()
    print ("\033[1;31m注：若输入多个汉字仅删除首位汉字\033[0m")
    word = input ("请输入你要移除的汉字：")
    word = word[0]
    word_file = os.path.join (os.getcwd(), 'All_words' , 'all_words.txt')
    words = open (word_file , 'r' , encoding='utf-8')
    if ((word[0] + '\n') not in words.readlines()):
        os.system ('cls')
        print ()
        print ("字库中没有该汉字！")
        print ()
        return 0
    words.seek(0)
    os.system ('cls')
    print ()
    print (f"\033[1;31m确认要删除汉字“{word}”吗？\033[0m(yes/no)")
    a = input()
    if (a == 'yes'):
        pass
    elif (a == 'no'):
        return 0
    else:
        os.system ('cls')
        print ("输入有误，默认拒绝。")
        return 0
    one_word = os.path.join (os.getcwd(), 'All_words' , word + '.txt')
    os.remove (one_word)
    new_lines = []
    for i in words.readlines():
        if (i == (word + '\n')):
            continue
        new_lines.append(i)
    words.close()
    new_file = open (word_file , 'w' , encoding='utf-8')
    for i in new_lines:
        new_file.write (i)
    new_file.close()
    os.system ('cls')
    print ()
    print (f"“{word}”汉字已移除！")
    print ()
    return 0